#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <shlwapi.h>
#include <d3d9.h>
#include "overlay.h"
#include "renderer.h"
#include <stdio.h>

HINSTANCE hDLL;

typedef IDirect3D9* (__stdcall *Direct3DCreate9_Type)(UINT);

OverlayRenderer* pRenderer = NULL;

DWORD WINAPI HookD3D9(LPVOID arg)
{
  if (GetModuleHandle(L"KappaUI.exe"))
    return 0;
  delete pRenderer;
  pRenderer = NULL;
  HMODULE hD3D9 = GetModuleHandle(L"d3d9.dll");
  HMODULE hD3D10 = GetModuleHandle(L"d3d10.dll");
  HMODULE hD3D11 = GetModuleHandle(L"d3d11.dll");
  if (hD3D9 == NULL && hD3D10 == NULL && hD3D11 == NULL) return 0;

  pRenderer = new OverlayRenderer(GetModuleHandle(NULL), hD3D9, hD3D10, hD3D11);

  return 0;
}

BOOL APIENTRY DllMain(HINSTANCE hModule, DWORD fdwReason, LPVOID lpReserved)
{
  if (fdwReason == DLL_PROCESS_ATTACH)
  {
    DisableThreadLibraryCalls(hModule);
    CreateThread(NULL, 0, HookD3D9, NULL, 0, NULL);
  }
  else if (fdwReason == DLL_PROCESS_DETACH)
  {
    delete pRenderer;
    pRenderer = NULL;
  }

  return TRUE;
}

OVERLAYDLL_API LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam) 
{
  if (nCode == HCBT_DESTROYWND && pRenderer)
    pRenderer->onDestroy((HWND) wParam);
  return CallNextHookEx(NULL, nCode, wParam, lParam); 
}
OVERLAYDLL_API LRESULT CALLBACK MouseHookProc(int nCode, WPARAM wParam, LPARAM lParam) 
{
  if (nCode < 0) return CallNextHookEx(NULL, nCode, wParam, lParam);

  if (pRenderer && pRenderer->onMouseEvent(wParam, (MOUSEHOOKSTRUCTEX*) lParam))
    return TRUE;

  return CallNextHookEx(NULL, nCode, wParam, lParam);
}
OVERLAYDLL_API LRESULT CALLBACK KeyboardHookProc(int nCode, WPARAM wParam, LPARAM lParam) 
{
  if (nCode < 0) return CallNextHookEx(NULL, nCode, wParam, lParam);

  if (pRenderer && pRenderer->onKeyEvent(wParam, lParam))
    return TRUE;

  return CallNextHookEx(NULL, nCode, wParam, lParam);
}
